<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

/**
 * Реализует элементы со множественным выбором типа "значение => имя"
 *
 * @author chaporgin_a
 */
abstract class VA_Form_FormElement_WithChoice extends VA_Form_FormElement {
    const POS_LABEL_LEFT = 'left';
    const POS_LABEL_RIGHT = 'right';
    private $labelPosition = null;
    const LAYOUT_LIST = 'list';
    const LAYOUT_INLINE = 'inline';
    private $groupLayout = null;
    private $choices = array();
    public function setDefaultByTitle($title) {
        if(in_array($title, $this->choices)) {
            $key = current(array_keys($this->choices, $title));
            $this->setValue($key);
        } else throw new Exception(sprintf('no choice with such title %s'
            , $title
            ));
    }
    public function setChoice($title, $value = null) {
        if(null === $value)
            $value = count($this->choices);
        $this->choices[$value] = $title;
    }
    public function getChoices() {
        return $this->choices;
    }
    public function setValue($key) {
        $this->value[] = $key;
        return $this;
    }
    public function getPrintableValue() {
        $return = array();
        foreach ($this->getValue() as $value) {
            $return[] = $this->choices[$value];
        }
        return join(', ',$return);
    }
    public function getSelectedTitles() {
        return $this->getPrintableValue();
    }
    public function  __construct() {
        parent::__construct();
        if(!is_array($this->value)) $this->value = array();
        $this->labelPosition = self::POS_LABEL_LEFT;
        $this->groupLayout = self::LAYOUT_INLINE;
    }
    public function setGroupLayout($layout) {
        if(!in_array($layout, array(self::LAYOUT_INLINE, self::LAYOUT_LIST)))
            throw new Exception('no such layout');
        $this->groupLayout = $layout;
        return $this;
    }
    public function getGroupLayout() {
        return $this->groupLayout;
    }
    public function setLabelPosition($position) {
        if(!in_array($position, array(self::POS_LABEL_LEFT, self::POS_LABEL_RIGHT)))
            throw new Exception('no such position');
        $this->labelPosition = $position;
        return $this;
    }
    public function getLabelPosition() {
        return $this->labelPosition;
    }
    public function getHTMLTagAttribute($name, $onlyValue = FALSE) {
        if($name == 'name')
            return 'name="'.parent::getHTMLTagAttribute($name, TRUE).'[]"';
        return parent::getHTMLTagAttribute($name, $onlyValue);
    }
    public function ResetValue() {
        $this->value = array();
    }
}

